var playpauseId = 'deddlfkkimgojlpjjbcdpmcnobmnoomn';

var first_run = false;
if (!localStorage.ran_before) {
  first_run = true;
  localStorage.ran_before = 1;
}

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
	sendResponse(eval(request));
});

chrome.extension.onRequestExternal.addListener(function(request, sender, sendResponse) {
	if (sender.id == '') return;
	sendResponse(eval(request));
});

function applyHotkeys(tabId, remove) {
	var indexes = localStorage.hotkeys?localStorage.hotkeys.split(','):[];
	if (tabId) {
		for (var i = 0; i < indexes.length; i++) {
			var item = Ext.decode(localStorage['hotkeys-' + indexes[i]]);
			if (!item.hotkey) continue;
			chrome.tabs.executeScript(tabId, {code: Ext.String.format('shortcut.remove("{0}")', item.hotkey)});
			chrome.tabs.executeScript(tabId, {code: Ext.String.format('shortcut.add("{0}", function() { chrome.extension.sendRequest("{1}"); }, {"disable_in_input": {2}});', item.hotkey, item.func, !item.inFields)});
		}
	} else {
		chrome.windows.getAll({populate: true}, function(windows){
			for (var j = 0; j < windows.length; j++) {
				var w = windows[j];
				for (var t = 0; t < w.tabs.length; t++) {
					var tabId = w.tabs[t].id;
					if (w.tabs[t].url.substring(0, 4) != 'http') continue;
					if (remove) chrome.tabs.executeScript(tabId, {code: Ext.String.format('shortcut.remove("{0}")', remove)});
					for (var i = 0; i < indexes.length; i++) {
						var item = Ext.decode(localStorage['hotkeys-' + indexes[i]]);
						if (!item.hotkey) continue;
						chrome.tabs.executeScript(tabId, {code: Ext.String.format('shortcut.remove("{0}")', item.hotkey)});
						chrome.tabs.executeScript(tabId, {code: Ext.String.format('shortcut.add("{0}", function() { chrome.extension.sendRequest("{1}"); }, {"disable_in_input": {2}});', item.hotkey, item.func, !item.inFields)});
					}
				}
			}
		});
	}
}

applyHotkeys();

var hotkeysStore;
Ext.onReady(function() {
	Ext.define('Hotkey', {
		extend: 'Ext.data.Model',
		fields: ['id', 'action', 'title', 'hotkey', {name: 'inFields', type: 'boolean', defaultValue: false}, 'func'],
	    proxy: {
	    	id: 'hotkeys',
	        type: 'localstorage',
	    }
	});

	hotkeysStore = new Ext.data.Store({
		model: 'Hotkey',
		autoSync: true
	});
	
	chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
		if (tab.url.substring(0, 4) != "http") return;
		//hotkeysStore.load();
/*
		hotkeysStore.data.each(function(item, index, totalItems) {
			if (item.get("hotkey")) {
				chrome.tabs.executeScript(tabId, {code: Ext.String.format('shortcut.remove("{0}")', item.get("hotkey"))});
				chrome.tabs.executeScript(tabId, {code: Ext.String.format('shortcut.add("{0}", function() { chrome.extension.sendRequest("{1}"); }, {"disable_in_input": {2}});', item.get("hotkey"), item.get("func"), item.get("inFields") != "1" )});
			}
		});
*/
		applyHotkeys(tabId);
	});
});

if (first_run) chrome.tabs.create({'url': chrome.extension.getURL('options.html?firstrun')});

function getArgs(query) {
	var args = new Object();
	var pairs = query.split("&");
	for(var i = 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf('=');
		if (pos == -1) continue;
		var argname = pairs[i].substring(0, pos);
		var value = pairs[i].substring(pos+1);
		args[argname] = unescape(value);
	}
	return args; 
}

function getAlbums() {
	if (!localStorage.token) return;
	Ext.Ajax.request({
		url: "https://api.vk.com/method/audio.getAlbums",
		method: "get",
		params: {
			access_token: localStorage.token
		},
		success: function(response) {
			var o = Ext.decode(response.responseText);
			if (typeof(o.response[0]) == 'number') o.response = o.response.slice(1);
			localStorage.albums = Ext.encode(o.response);
		},
		failure: function(response, opts) {
			localStorage.removeItem("albums");
		}
	});
}

function login(callback) {
	if (chrome && chrome.windows && chrome.windows.create) {
		chrome.windows.create({
			url: "http://oauth.vk.com/authorize?client_id=2847164&scope=audio&redirect_uri=http://api.vk.com/blank.html&display=popup&response_type=token",
			height: 1,
			width: 1,
			type: "popup",
			focused: true
		}, function(window) {
				chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
					if (tabId == window.tabs[0].id && changeInfo.status == "complete" && tab.url.indexOf('#') >= 0) {
						var query = tab.url.substring(tab.url.indexOf('#') + 1);
						var args = getArgs(query);
						if (args.access_token) {
							localStorage.token = args.access_token;
							localStorage.userId = args.user_id;
							localStorage.expires = new Date() - 0 + args.expires_in * 1000;
							Ext.Ajax.request({
								url: "https://api.vk.com/method/users.get",
								method: "get",
								params: {
									uids: localStorage.userId,
									access_token: localStorage.token,
									fields: "first_name,last_name"
								},
								success: function(response) {
									var obj = Ext.decode(response.responseText);
									localStorage.firstName = obj.response[0].first_name;
									localStorage.lastName = obj.response[0].last_name;
									if (callback) callback();
								},
								failure: function(response, opts) {
									localStorage.removeItem("firstName");
									localStorage.removeItem("lastName");
									if (callback) callback();
								}
							});
							getAlbums();
						} else {
							localStorage.removeItem("token");
							localStorage.removeItem("userId");
						}
						chrome.windows.remove(window.id);
					}
				});
			}
		);
	}
}

if (!localStorage.token || localStorage.expires < new Date - 0) login();